package com.ruoyi.web.controller.custom;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.QrCodeUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.RnxInviteLog;
import com.ruoyi.system.domain.RnxRoster;
import com.ruoyi.system.service.IRnxInviteLogService;
import com.ruoyi.system.service.IRnxRosterService;
import org.apache.commons.codec.binary.Base64;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * 员工花名册Controller
 *
 * @author ruoyi
 * @date 2022-04-28
 */
@Controller
@RequestMapping("/system/roster")
public class RnxRosterController extends BaseController {
	private String prefix = "system/roster";

	@Autowired
	private IRnxRosterService rnxRosterService;

	@Autowired
	private IRnxInviteLogService rnxInviteLogService;

	@RequiresPermissions("system:roster:view")
	@GetMapping()
	public String roster() {
		return prefix + "/roster";
	}


	/**
	 * 邀请页面
	 * @return
	 */
	@RequiresPermissions("system:roster:invite")
	@GetMapping("/inviteUser")
	public String inviteUser(){
		return  prefix + "/inviteUser";
	}

	/**
	 * 邀请保存
	 */
	@PostMapping("/saveInvite")
	@ResponseBody
	@Log(title = "邀请记录", businessType = BusinessType.INSERT)
	public AjaxResult saveInvite(RnxInviteLog rnxInviteLog){
		String phone = rnxInviteLog.getMobilePhone();
		RnxInviteLog inviteLog = rnxInviteLogService.selectRnxInviteLogByPhone(phone);
		if(inviteLog != null){
			return AjaxResult.error("不能重复邀请!");
		}
		rnxInviteLog.setInviteTime(new Date());
		//默认待填写
		rnxInviteLog.setState(1L);
		return toAjax(rnxInviteLogService.insertRnxInviteLog(rnxInviteLog));
	}

	/**
	 *  查询员工花名册列表
	 */
	@RequiresPermissions("system:roster:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(RnxRoster rnxRoster) {
		startPage();
		List<RnxRoster> list = rnxRosterService.selectRnxRosterList(rnxRoster);
		return getDataTable(list);
	}

	/**
	 * 导出员工花名册列表
	 */
	@RequiresPermissions("system:roster:export")
	@Log(title = "员工花名册", businessType = BusinessType.EXPORT)
	@PostMapping("/export")
	@ResponseBody
	public AjaxResult export(RnxRoster rnxRoster) {
		List<RnxRoster> list = rnxRosterService.selectRnxRosterList(rnxRoster);
		ExcelUtil<RnxRoster> util = new ExcelUtil<RnxRoster>(RnxRoster.class);
		return util.exportExcel(list, "全量员工花名册数据");
	}

	/**
	 * 导出员工花名册列表-选中
	 */
	@RequiresPermissions("system:roster:export")
	@Log(title = "员工花名册部分导出", businessType = BusinessType.EXPORT)
	@PostMapping("/exportCheck")
	@ResponseBody
	public AjaxResult exportCheck(@RequestBody List<Long> ids) {
		logger.info("exportCheck ids:"+ids);
		List<RnxRoster> list = new LinkedList<>();
		if(ids.size()>0){
			ids.forEach( i-> list.add(rnxRosterService.selectRnxRosterById(i)));
		}
		if(list.size() == 0){
			return AjaxResult.error("暂无数据!");
		}
		ExcelUtil<RnxRoster> util = new ExcelUtil<RnxRoster>(RnxRoster.class);
		return util.exportExcel(list, "部分员工花名册数据");
	}

	/**
	 * 新增员工花名册
	 */
	@GetMapping("/add")
	public String add() {
		return prefix + "/add";
	}

	/**
	 * 新增保存员工花名册
	 */
	@RequiresPermissions("system:roster:add")
	@Log(title = "员工花名册", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public AjaxResult addSave(RnxRoster rnxRoster) {
		return toAjax(rnxRosterService.insertRnxRoster(rnxRoster));
	}

	/**
	 * 修改员工花名册
	 */
	@GetMapping("/edit/{id}")
	public String edit(@PathVariable("id") Long id, ModelMap mmap) {
		RnxRoster rnxRoster =
				rnxRosterService.selectRnxRosterById(id);
		mmap.put("rnxRoster", rnxRoster);
		return prefix + "/edit";
	}

	/**
	 * 修改保存员工花名册
	 */
	@RequiresPermissions("system:roster:edit")
	@Log(title = "员工花名册", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public AjaxResult editSave(RnxRoster rnxRoster) {
		return toAjax(rnxRosterService.updateRnxRoster(rnxRoster));
	}

	/**
	 * 删除员工花名册
	 */
	@RequiresPermissions("system:roster:remove")
	@Log(title = "员工花名册", businessType = BusinessType.DELETE)
	@PostMapping("/remove")
	@ResponseBody
	public AjaxResult remove(String ids) {
		return toAjax(rnxRosterService.deleteRnxRosterByIds(ids));
	}

	@PostMapping("/import")
	@Log(title = "员工花名册", businessType = BusinessType.IMPORT)
	@ResponseBody
	public AjaxResult importRoster(MultipartFile file)throws Exception
	{
		ExcelUtil<RnxRoster> rnxRosterExcelUtil = new ExcelUtil<>(RnxRoster.class);
		List<RnxRoster> list = rnxRosterExcelUtil.importExcel(file.getInputStream());
		if(list != null && list.size()>0){
			list.stream().forEach(r -> rnxRosterService.insertRnxRoster(r));
		}
		return AjaxResult.success("导入成功!");
	}

	@GetMapping("/importTemplate")
	@ResponseBody
	public AjaxResult importTemplate()
	{
		ExcelUtil<RnxRoster> util = new ExcelUtil<>(RnxRoster.class);
		return util.importTemplateExcel("员工花名册模板");
	}

	/**
	 * 查看详情
	 * @param id
	 * @param mmap
	 * @return
	 */
	@RequiresPermissions("system:roster:detail")
	@GetMapping("/detail/{id}")
	public String detail(@PathVariable("id") Long id, ModelMap mmap)
	{
		mmap.put("rnxRoster", rnxRosterService.selectRnxRosterById(id));
		return prefix + "/detail";
	}

	/**
	 * 生成二维码
	 * @param phone
	 * @return
	 */
	@GetMapping("/invite/{phone}")
	@ResponseBody
	public AjaxResult generateQrCode(@PathVariable(value = "phone")String phone){
		//确认是否已经生成
		String qrName = "/invite_"+phone+".jpg";
		File file = new File(RuoYiConfig.getUploadPath()+ Constants.RESOURCE_PREFIX + qrName);
		if(!file.exists()){
			try {
				logger.info("正在生成二维码--->" + qrName);
				QrCodeUtils.generateCode(phone);
				logger.info("二维码已生成--->" + qrName);
			} catch (Exception e) {
				return AjaxResult.error("二维码生成失败!");
			}
		}
		return AjaxResult.success("二维码已生成",Constants.RESOURCE_PREFIX + "/upload" + qrName);
	}

	/**
	 * 生成二维码 + 返回流
	 * @param phone
	 * @return
	 */
	@GetMapping("/invite2/{phone}")
	@ResponseBody
	public AjaxResult generateQrCode2(@PathVariable(value = "phone")String phone,HttpServletResponse response){
		//确认是否已经生成
		String qrName = "/invite_"+phone+".jpg";
		File file = new File(RuoYiConfig.getUploadPath() + qrName);
		if(!file.exists()){
			try {
				logger.info("正在生成二维码--->" + qrName);
				QrCodeUtils.generateCode(phone);
				logger.info("二维码已生成--->" + qrName);

			} catch (Exception e) {
				logger.error("二维码生成异常：",e);
				return AjaxResult.error("二维码生成异常!");
			}
		}
		byte[] data;
		try {
			InputStream in = new FileInputStream(file);
			data = new byte[in.available()];
			in.read(data);
		}catch (Exception e){
			logger.error("二维码输出异常：",e);
			return AjaxResult.error("二维码输出异常!");
		}
		String s = new String(Base64.encodeBase64(data));
		return AjaxResult.success("success",s);
	}
}
